<template>
  <div class="content">
    <ul class="list" id="list"></ul>
  </div>
</template>

<script>
import menuList from '../utils/menuList';

export default {
  name: 'FaltArray',
  data () {
    return {
      data: menuList.data
    }
  },
  mounted () {
    this.createHTML(this.data)
    this. init()
  },
  methods: {
    init () {
      let datas = menuList.data
      this.flat(datas)
      this.flatArray(datas)
      // console.log(this.flatArray(datas))
    },
    flatArray (items) {
      return items.reduce( (prev, current) => {
        return prev.concat(current, Array.isArray(current.children) ? this.flatArray(current.children) : [] )
      }, [])
    },
    flat (items) {
      let arr = []
      items.forEach( item => {
        arr.push(item)
        if (Array.isArray(item.children)) {
          arr =  arr.concat(this.flat(item.children))
        }
      } )
      arr.filter( item => {
        if (item.checked) {
          console.log(item)
          return item
        }
      })
      return arr
    },
    createHTML (items, level = 0) {
      let ulElement = document.querySelector('#list')
      return ulElement.innerHTML = items.map( item => {
        let str = `<li style="padding-left:${level * 30}px">
        <input type="checkbox" ${item.checked ? 'checked' : ''} />
          <span>${item.name}</span>
        </li>`

        if (Array.isArray(item.children)) {
          str += this.createHTML(item.children, level +1)
        }
        return str
      } ).join('')
    }
  }
}
</script>

<style lang="less" scoped>

</style>
